<template>
  <div class="PlayPageLyric">
   
      <ul ref="list" :style="{ transform: `translateY(${-offsetH}px)` }">
        <li
          v-for="(item, index) in songLyric"
          :key="index"
          :class="{ active: index == currentLyric.index }"
        >
          {{ item.text }}
        </li>
      </ul>
   
  </div>
</template>

<script>
export default {
  props: ["playsong", "durationchange"],
  data: function () {
    return {
      lyrics: "",
      offsetH: 0,
    };
  },

  created: function () {
    this.axios
      .get("https://apis.netstart.cn/music/lyric?id=" + this.playsong.id)
      .then((res) => {
        console.log(res.data.lrc);
        this.lyrics = res.data.lrc.lyric;
      });
  },

  methods: {
    songLyrics: function (strLyric) {
      return strLyric
        .split("\n")
        .filter((ly) => ly)
        .map((ly) => {
          var lys = ly.match(/^\[(\d{2}:\d{2}\.\d{2,3})\](.*)/);
          var newlys = lys[1].split(":");
          return {
            time: newlys[0] * 60 + newlys[1] * 1,
            text: lys[2],
          };
        });
    },
    findLyrics: function (songLyric, durationchange) {
      var lystime = songLyric.filter((lyst) => {
        return lyst.time < durationchange;
      });
      return {
        index: lystime.length - 1,
        lyrics: lystime[length - 1],
      };
    },
  },

  computed: {
    songLyric: function () {
      return this.songLyrics(this.lyrics);
    },
    currentLyric: function () {
      return this.findLyrics(this.songLyric, this.durationchange);
    },
  },

  watch: {
    "currentLyric.index": function (n) {
      var h = [...this.$refs.list.querySelectorAll("li")]
        .slice(0, n)
        .reduce(function (total, element) {
          return total + Number(element.offsetHeight);
        }, 0);

      var offsetH;
      if (h < 513 / 2) {
        offsetH = 0;
      } else if (h > Number(this.$refs.list.offsetHeight) - 513 / 2) {
        offsetH =Number(this.$refs.list.offsetHeight)  - 513;
      } else {
        offsetH = h - 513 / 2;
      }
      this.offsetH = offsetH;
    },
  },
};
</script>

<style lang="less" scoped>
.PlayPageLyric {
  flex: 1;
  overflow: hidden;
  padding: 5px 0;
    ul {
      padding: 0;
      transition: all 0.4s;
      li {
        margin:5px 0;
        padding: 0;
        list-style: none;
        color: rgb(160, 156, 156);
        font-size: 15px;
        text-align: center;
        &.active {
          color: red;
        }
      }
    }
  
}
</style>